<template>
  <div class="component-upload-video">
    <el-upload
      multiple
      :action="uploadVideoUrl"
      list-type="text"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      ref="videoUpload"
      :on-remove="handleDelete"
      :show-file-list="true"
      :headers="headers"
      :file-list="fileList"
      :on-preview="handleVideoPreview"
      :class="{ hide: fileList.length >= limit }"
    >
      <el-button type="primary" icon="el-icon-upload">上传视频</el-button>
    </el-upload>

    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
      <template v-if="fileType">格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
      的视频文件
    </div>

    <!-- 视频预览弹窗 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="视频预览"
      width="800"
      append-to-body
      @closed="handleDialogClosed"
    >
      <video
        v-if="dialogVideoUrl"
        ref="previewVideo"
        :src="dialogVideoUrl"
        controls
        autoplay
        style="display: block; max-width: 100%; margin: 0 auto"
      ></video>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { isExternal } from "@/utils/validate";
import { deleteFromOss } from "@/api/kiku/common";

export default {
  name: "OssVideoUpload",
  props: {
    value: {
      type: [String, Object, Array],
      default: ""
    },
    limit: {
      type: Number,
      default: 3,
      validator: value => value > 0
    },
    fileSize: {
      type: Number,
      default: 100,
      validator: value => value > 0
    },
    fileType: {
      type: Array,
      default: () => ["mp4", "avi", "mov", "wmv"],
      validator: value => value.every(type => typeof type === "string")
    },
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogVideoUrl: "",
      dialogVisible: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadVideoUrl: `https://manage.kiku001.top/prod-api/common/uploadVideoToOss`,
      headers: {
        Authorization: `Bearer ${getToken()}`
      },
      fileList: []
    };
  },
  computed: {
    showTip() {
      return this.isShowTip && (this.fileType.length > 0 || this.fileSize > 0);
    }
  },
  watch: {
    value: {
      handler(val) {
        this.updateFileList(val);
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    updateFileList(val) {
      if (!val) {
        this.fileList = [];
        return;
      }
      const list = Array.isArray(val) ? val : val.toString().split(",");
      this.fileList = list.map(item => {
        if (typeof item === "string") {
          const url = this.normalizeUrl(item);
          return { name: url, url };
        }
        return item;
      });
    },
    normalizeUrl(url) {
      if (!url) return url;
      if (isExternal(url) || url.startsWith(this.baseUrl)) {
        return url;
      }
      return `${this.baseUrl}${url}`;
    },
    handleBeforeUpload(file) {
      const extension = file.name.split(".").pop().toLowerCase();
      const typeValid = this.fileType.includes(extension);
      if (!typeValid) {
        this.$modal.msgError(`请上传 ${this.fileType.join("/")} 格式的视频文件!`);
        return false;
      }
      if (file.name.includes(",")) {
        this.$modal.msgError("文件名不能包含英文逗号!");
        return false;
      }
      const sizeValid = file.size / 1024 / 1024 < this.fileSize;
      if (!sizeValid) {
        this.$modal.msgError(`视频大小不能超过 ${this.fileSize}MB!`);
        return false;
      }
      this.$modal.loading("正在上传视频，请稍候...");
      this.number++;
      return true;
    },
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.fileName, url: res.url });
        this.uploadedSuccessfully();
      } else {
        this.handleUploadError(res.msg);
        this.$refs.videoUpload.handleRemove(file);
      }
    },
    handleUploadError(err) {
      this.number--;
      this.$modal.closeLoading();
      const errorMsg = typeof err === "string" ? err : "上传视频失败，请重试";
      this.$modal.msgError(errorMsg);
    },
    handleExceed() {
      this.$modal.msgError(`最多只能上传 ${this.limit} 个视频!`);
    },
    async handleDelete(file) {
      try {
        const ossUrl = new URL(file.url);
        const fileName = ossUrl.pathname.substring(1);
        await deleteFromOss(fileName);
        this.$modal.msgSuccess("删除成功");
        this.fileList = this.fileList.filter(item => item.url !== file.url);
        this.$emit("input", this.listToString(this.fileList));
      } catch (error) {
        const errorMsg = error.response?.data?.msg || error.message || "删除失败";
        this.$modal.msgError(`删除失败: ${errorMsg}`);
      }
    },
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = [...this.fileList, ...this.uploadList];
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    handleVideoPreview(file) {
      this.dialogVideoUrl = file.url;
      this.dialogVisible = true;
    },
    handleDialogClosed() {
      // 关闭弹窗时暂停视频并重置
      const videoEl = this.$refs.previewVideo;
      if (videoEl) {
        videoEl.pause();
        videoEl.currentTime = 0;
        videoEl.removeAttribute("src"); // 释放资源
        videoEl.load();
      }
      this.dialogVideoUrl = "";
    },
    listToString(list, separator = ",") {
      return list
        .map(item => item.url.replace(this.baseUrl, ""))
        .filter(url => url)
        .join(separator);
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep.hide .el-upload {
  display: none;
}
</style>
